import React from "react";
import { Alert } from 'antd';
import { viewTypes } from "../../../../constants/form";
import FBFooterView from "../component/form-footer/View";
import FBHeaderView from "../component/form-header/View";
import { isLayout, isDataTable } from "../component/typeof";
import { Consumer } from "../theme";
import FieldView from "./field/View";
import "./Main.less";
import {WeaLocaleProvider} from "ecCom";
import classNames from 'classnames';
import isMobile from "../../../../utils/mobileDetect";

const getLabel = WeaLocaleProvider.getLabel;
const formatMultiLang = WeaLocaleProvider.formatMultiLang;
const { READONLY } = viewTypes;
const isMobileView = isMobile();
const Divider = ({ divider }) => {
  const { visible, color } = divider;

  if (!visible) return null;

  return <div style={{ borderBottom: `1px solid ${color}` }} />
}


export default class FormMainView extends React.Component {
  constructor() {
    super();

    this.onValueChange = _.memoize(this.onValueChange.bind(this));
  }

  onValueChange(uuid) {
    return value => this.props.onValueChange(uuid, value);
  }

  renderItem = (com, customProps = {}) => {
    if (!com) return null;
    
    if (com.pid) {
      const coms = this.props.components;
      const parentCom = coms.find(({ uuid }) => uuid === com.pid);

      if (isLayout(parentCom)) {
        com = coms.find(({ uuid }) => uuid === com.uuid);
      }
    }

    if (!this.checkVisible(com)) return null;
    
    const { errorCom, error } = com;
    let theError = '';

    if (customProps.hasOwnProperty('error')) {
      theError = customProps.error;
    } else if (errorCom) {
      theError = errorCom.error;
    } else {
      theError = error;
    }

    return this.getFieldView(com, customProps, theError);
  }

  checkVisible = com => {
    const { components } = this.props;
    const childComs = com.config.coms;

    if (childComs && isLayout(com)) {
      return !!childComs.find( childCom => {
        if (childCom) {
          let child = components.find(component => component.uuid === childCom.uuid);
          return child.visible;
        }
        return false; 
      });
    }

    return com.visible;
  }

  getFieldView(com, customProps, error) {
    const { viewType, onValueChange, toggleFooterDisable, shortkey, baseData, editBaseInfo, isEdit } = this.props;
    const errmsg = !error ? null : <p className='wea-edc-errmsg'>{error}</p>;
    const propViewType = customProps.viewType ? customProps.viewType : '';
    const comProps = {
      viewType: propViewType || viewType,
      key: com.uuid,
      field: com,
      className: errmsg && !isDataTable(com) && 'wea-edc-has-error',
      children: errmsg,
      shortkey: shortkey,
      baseInfo: baseData,
      editBaseInfo: editBaseInfo,
      isEdit: isEdit
    };
    
    // 多字段混合插件， 如地址
    if(com.config.complex) {
      return (
        <FieldView ecId={`${this && this.props && this.props.ecId || ''}_FieldView@5zkc72`}
          {...comProps}
          onChange={onValueChange}
          {...customProps}
        />
      );
    }

    // 布局插件，如明细子表
    if (com.config.coms) {
      return (
        <FieldView ecId={`${this && this.props && this.props.ecId || ''}_FieldView@5ndo6l`} 
          {...comProps}
          onChange={this.onValueChange(com.uuid)}
          renderItem={this.renderItem}
        />
      );
    }

    return (
      <FieldView ecId={`${this && this.props && this.props.ecId || ''}_FieldView@56ar52`}
        onChange={this.onValueChange(com.uuid)}
        toggleFooterDisable={toggleFooterDisable}
        {...customProps}
        {...comProps}
      />
    );
  }

  render() {
    const {
      formHeader,
      formFooter,
      components,
      onSubmit,
      viewType,
      showHeader = true,
      theme,
      baseData,
      noEdit
    } = this.props;

    if(!components) return null;

    const bgColor = (theme && theme.header.type == 0) ? theme.header.css.backgroundColor : '#0270c1';
    const titleCss = (theme && theme.title) ? theme.title.css : {};

    return (
      <Consumer ecId={`${this && this.props && this.props.ecId || ''}_Consumer@7artwn`}>
        {({ form }) => (
          <div className='wea-edc-fv-main' style={Object.assign(form.css, form.border.css)}>
            { noEdit ?
              <div className={classNames('wea-edc-form-no-edit-tip', {'wea-edc-form-no-edit-tip-mobile': isMobileView })} >
                <Alert ecId={`${this && this.props && this.props.ecId || ''}_Alert@nlcmtn`} message={getLabel(523081, "提示：您不参与此次表单填写")} type="warning" showIcon />
              </div> : null
            }
            { showHeader ? <FBHeaderView ecId={`${this && this.props && this.props.ecId || ''}_FBHeaderView@hci3fj`} data={formHeader.config} /> : 
              <div>
                { (formHeader && formHeader.config && formHeader.config.title) ?
                  <p className='fheader-title' style={titleCss}>{formatMultiLang(formHeader.config.title)}</p> : null
                }
                { (formHeader && formHeader.config && formHeader.config.desc) ?
                  <p className='fheader-desc' dangerouslySetInnerHTML={{__html: formHeader.config.desc}}></p> : null
                }
              </div>
            }
            <Divider ecId={`${this && this.props && this.props.ecId || ''}_Divider@eorl6v`} divider={form.divider} />
              <div className='wea-edc-fv-body clearfix'>
                {
                  noEdit ? 
                  <div className='wea-edc-fv-body-mask'></div> : null
                }
                {
                  viewType === READONLY ?
                  <div className='wea-edc-form-item'>
                    <div className='wea-edc-edit-date'>
                      {getLabel(523082, '填写人')}：{baseData.creator}
                      <span>{getLabel(523083, '填写时间')}：{baseData.createdate} {baseData.createtime}{baseData.statisticsdate && ' (' + getLabel(523084,'补交') + baseData.statisticsdate + ')'}</span>
                    </div>
                  </div>
                  : null
                }
                {components.filter(com => !com.pid && com.visible).map(com => {
                  return this.renderItem(com);
                })}
              </div>
              <Divider ecId={`${this && this.props && this.props.ecId || ''}_Divider@6qs588`} divider={form.divider} />
              {
                (viewType === READONLY || noEdit) ? null :
                <FBFooterView ecId={`${this && this.props && this.props.ecId || ''}_FBFooterView@ztjd0d`}
                  data={formFooter.config}
                  loading={formFooter.loading}
                  disable={formFooter.disable}
                  onSubmit={onSubmit}
                />
              }
              
          </div>
        )}
      </Consumer>
    );
  }
}

FormMainView.defaultProps = {
  formHeader: null,
  formFooter: null,
  components: null,
  wrapperDOM: document.body,
  viewType: viewTypes.PC,
  onSubmit: () => { },
  onValueChange: () => { }
};